package esms.etonenet.boss1069.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.etonenet.taglibs.component.AjaxPage;
import com.etonenet.taglibs.util.AjaxPageUtil;
import com.etonenet.util.StringUtil;

import esms.etonenet.boss1069.enums.mtmo.MoState;
import esms.etonenet.boss1069.enums.mtmo.RtErrorCode;
import esms.etonenet.boss1069.mtmo.Mo;
import esms.etonenet.boss1069.service.biz.impl.MoService;
import esms.etonenet.boss1069.util.AutocompleteUtil;
import esms.etonenet.boss1069.util.TilesUtil;
import esms.etonenet.boss1069.web.Autocomplete;
import esms.etonenet.boss1069.web.PageRequest;
import esms.etonenet.boss1069.web.SpecificationCondition;
import esms.etonenet.boss1069.web.SpecificationHelper;
import esms.etonenet.boss1069.web.UrlConstants;
import esms.etonenet.bossoa.entity.CarrierCode;
import esms.etonenet.bossoa.entity.City;
import esms.etonenet.bossoa.entity.Country;
import esms.etonenet.bossoa.entity.Province;
import esms.etonenet.bossoa.repository.CarrierCodeRepository;
import esms.etonenet.bossoa.repository.CityRepository;
import esms.etonenet.bossoa.repository.CountryRepository;
import esms.etonenet.bossoa.repository.ProvinceRepository;
import esms.etonenet.oldboss.entity.OldSpService;
import esms.etonenet.oldboss.entity.OldSpServicePK;
import esms.etonenet.oldboss.repository.OldChannelRepository;
import esms.etonenet.oldboss.repository.OldSpRepository;
import esms.etonenet.oldboss.repository.OldSpServiceRepository;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@Controller
public class QxxxglMoController {

	@Resource
	private MoService ttMoService;

	@Resource
	private OldSpRepository spEm;

	@Resource
	private OldChannelRepository channelEm;

	@Resource
	private CountryRepository countryEm;

	@Resource
	private ProvinceRepository provinceEm;

	@Resource
	private CityRepository cityEm;

	@Resource
	private CarrierCodeRepository carrierCodeEm;

	@Resource
	private OldSpServiceRepository spServiceEm;

	/**
	 * 企信上行查询初始化
	 * 
	 * @return
	 */
	@RequestMapping(UrlConstants.QYDX_QXXXGL_MOSELECT_INDEX)
	public ModelAndView mtSelectIndex() {

		ModelAndView mav = new ModelAndView(TilesUtil.getPath(UrlConstants.QYDX_QXXXGL_MOSELECT_INDEX));
		mav.addObject("rtErrorCode", RtErrorCode.toDisplayMap2());
		mav.addObject("smsMoState", MoState.toDisplayMap2());
		return mav;

	}

	/**
	 * 企信上行查询展示
	 * 
	 * @return
	 */
	@RequestMapping(UrlConstants.QYDX_QXXXGL_MOSELECT_DATA)
	@ResponseBody
	public AjaxPage data(Integer pageNumber, Integer pageSize, final String sortName, final String sortOrder,
			final String spIdName, final String channelId, final Mo mo,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date smStartTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date smEndTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date mcStartTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") final Date mcEndTime, final String countryIdName,
			final String provinceIdName, final String cityIdName, final String rtErrorCode,
			HttpServletRequest request) {
		Map<String, String[]> map = request.getParameterMap();
		boolean b = map.containsKey("smStartTime");

		List<SpecificationCondition> conditions = new ArrayList<SpecificationCondition>();
		conditions.add(SpecificationCondition.eq("spId", StringUtil.splitMinusFirstGroup(spIdName)));
		conditions.add(SpecificationCondition.eq("spServiceCode", mo.getSpServiceCode()));
		conditions.add(SpecificationCondition.eq("channelId", StringUtil.splitMinusFirstGroup(channelId)));
		if (!b) {
			conditions.add(SpecificationCondition.lessOrEqual("spMoTime",
					DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH)));
			conditions.add(SpecificationCondition.greater("spMoTime",
					DateUtils.truncate(DateUtils.addDays(new Date(), 1), Calendar.DAY_OF_MONTH)));
		} else {
			if (smStartTime != null)
				conditions.add(SpecificationCondition.greaterOrEqual("carrierMoTime", smStartTime));
			if (smEndTime != null)
				conditions.add(SpecificationCondition.lessOrEqual("carrierMoTime", smEndTime));
		}
		if (mcStartTime != null)
			conditions.add(SpecificationCondition.greaterOrEqual("spMoTime", mcStartTime));
		if (mcEndTime != null)
			conditions.add(SpecificationCondition.lessOrEqual("spMoTime", mcEndTime));
		if (mo.getMoState() != null)
			conditions.add(
					SpecificationCondition.eq("moState", StringUtil.splitMinusFirstGroup(mo.getMoState().toString())));
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("destinationAddr", mo.getDestinationAddr()));
		conditions.add(SpecificationCondition.eq("countryCode", StringUtil.splitMinusFirstGroup(countryIdName)));
		conditions.add(SpecificationCondition.eq("provinceCode", StringUtil.splitMinusFirstGroup(provinceIdName)));
		conditions.add(SpecificationCondition.eq("cityCode", StringUtil.splitMinusFirstGroup(cityIdName)));
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("moStat", mo.getMoStat()));
		conditions.add(SpecificationCondition.eq("moErr", StringUtil.splitMinusFirstGroup(rtErrorCode)));

		SpecificationHelper<Mo> sh = new SpecificationHelper<>(conditions, sortOrder, sortName);
		Page<Mo> p = ttMoService.page(sh.createSpecification(), new PageRequest(pageNumber, pageSize));
		for (Mo mo2 : p) {
			displaySpMoBaseInfo(mo2);
		}

		return AjaxPageUtil.toAjaxPage(p.getTotalElements(), p.getContent());

	}

	/**
	 * 修正基础信息显示国家、省、城市、营运商、消息内容、sp服务代码
	 * 
	 * @param mo
	 */
	private void displaySpMoBaseInfo(Mo mo) {

		if (StringUtil.isNotEmpty(mo.getCarrierCode())) {
			CarrierCode cc = carrierCodeEm.findOne(mo.getCarrierCode());
			if (cc != null)
				mo.setCarrierCode(cc.getCarrierCode() + "-" + cc.getCarrierName());
		}
		if (StringUtil.isNotEmpty(mo.getCountryCode())) {
			Country country = countryEm.findOne(mo.getCountryCode());
			if (country != null)
				mo.setCountryCode(country.getCountryCode() + "-" + country.getCountryName());
		}
		if (StringUtil.isNotEmpty(mo.getProvinceCode())) {
			Province province = provinceEm.findOne(mo.getProvinceCode());
			if (province != null)
				mo.setProvinceCode(province.getProvinceCode() + "-" + province.getProvinceName());
		}
		if (StringUtil.isNotEmpty(mo.getCityCode())) {
			City city = cityEm.findOne(mo.getCityCode());
			if (city != null)
				mo.setCityCode(city.getCityCode() + "-" + city.getCityName());
		}
		if (StringUtil.isNotEmpty(mo.getShortMessage()) && mo.getDataCoding() != null) {
			mo.setShortMessage(StringUtil.decodeHexString(mo.getDataCoding(), mo.getShortMessage()));
		}
		if (StringUtil.isNotEmpty(mo.getSpId())) {
			OldSpServicePK ssp = new OldSpServicePK();
			ssp.setSpId(mo.getSpId());
			ssp.setSpServiceCode(mo.getSpServiceCode());
			OldSpService spService = spServiceEm.findOne(ssp);
			if (spService != null)
				mo.setSpServiceCode(mo.getSpServiceCode() + "(" + spService.getSpServiceName() + ")");
		}
	}

	// sp服务代码
	@RequestMapping(UrlConstants.QYDX_QXXXGL_MOSELECT_AUTOCOMPLETE_SP_SERVICECODE)
	@ResponseBody
	public List<Autocomplete> autoSpserviceSpServiceCode(String term, String spIdName) {

		return AutocompleteUtil.object2auto(spServiceEm.autoSpServiceCode(term, spIdName.split("-")[0]));
	}

	// sp
	@RequestMapping(UrlConstants.QYDX_QXXXGL_MOSELECT_AUTOCOMPLETE_SP)
	@ResponseBody
	public List<Autocomplete> autoSpmtrouteSp(String term) {
		return AutocompleteUtil.object2auto(spEm.autoSP(term));
	}

	// 通道
	@RequestMapping(UrlConstants.QYDX_QXXXGL_MOSELECT_AUTOCOMPLETE_CHANNEL)
	@ResponseBody
	public List<Autocomplete> autoSpmtrouteChannel(String term) {

		return AutocompleteUtil.object2auto(channelEm.autoChannel(term));
	}

	// 国家代码
	@RequestMapping(UrlConstants.QYDX_QXXXGL_AUTOCOMPLETE_COUNTRY2)
	@ResponseBody
	public List<Autocomplete> autoCountry(String term) {

		List<Autocomplete> country = new ArrayList<>();
		country.addAll(AutocompleteUtil.object2auto(countryEm.auto(term)));

		return country;
	}

	// 省代码
	@RequestMapping(UrlConstants.QYDX_QXXXGL_AUTOCOMPLETE_PROVINCE2)
	@ResponseBody
	public List<Autocomplete> autoProvince(String countryIdName, String term) {

		List<Autocomplete> province = new ArrayList<>();
		province.addAll(AutocompleteUtil.object2auto(provinceEm.auto(countryIdName.split("-")[0], term)));

		return province;
	}

	// 市代码
	@RequestMapping(UrlConstants.QYDX_QXXXGL_AUTOCOMPLETE_CITY2)
	@ResponseBody
	public List<Autocomplete> autoCity(String provinceIdName, String term) {

		List<Autocomplete> city = new ArrayList<>();
		city.addAll(AutocompleteUtil.object2auto(cityEm.auto(provinceIdName.split("-")[0], term)));

		return city;
	}

}
